package com.xjrsoft.module.base.utils;

import com.xjrsoft.core.tool.node.ForestNodeMerger;
import com.xjrsoft.core.tool.node.INode;
import com.xjrsoft.core.tool.utils.BeanUtil;
import com.xjrsoft.core.tool.utils.CollectionUtil;
import com.xjrsoft.core.tool.utils.StringPool;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.base.vo.CompanyParentTreeVo;

import java.util.ArrayList;
import java.util.List;

public final class TreeNodeUtil {
    private TreeNodeUtil(){}


    public static void findChildrenId(INode node, List<String> childIdList) {
        List<INode> children = node.getChildren();
        if (CollectionUtil.isNotEmpty(children)) {
            for (INode child : children) {
                findChildrenId(child, childIdList);
            }
        }
        childIdList.add(node.getId());
    }

    public static <T extends INode> List<T> getNodeListOfTree(T entity) {
        List<T> resultList = new ArrayList<>();
        List<T> children = entity.getChildren();
        if (CollectionUtil.isNotEmpty(children)) {
            for (T node : children) {
                resultList.addAll(getNodeListOfTree(node));
            }
        }
        resultList.add(entity);
        return resultList;
    }

    public static List<INode> getNodeAndChildrenList(String objectId, String cacheKey) {
        List<? extends INode> cacheList = OrganizationCacheUtil.getNodeListCaches(cacheKey);
        ForestNodeMerger.merge(cacheList);
        INode targetNode = null;
        for (INode node : cacheList) {
            if (StringUtil.equals(objectId, node.getId())) {
                targetNode = node;
                break;
            }
        }
        return getNodeListOfTree(targetNode);
    }

    public static void buildCompanyParentTree(List<CompanyParentTreeVo> list){
        for (CompanyParentTreeVo item : list) {
            String parentId = item.getParentId();
            if (StringUtil.isEmpty(parentId) || StringUtil.equalsIgnoreCase(parentId, StringPool.ZERO)) {
                continue;
            }
            for (CompanyParentTreeVo company : list) {
                if (StringUtil.equals(item.getParentId(), company.getCompanyId())) {
                    item.setParent(company);
                    break;
                }
            }
        }
    }

    public static List<CompanyParentTreeVo> findParentCompanyList(CompanyParentTreeVo companyParentTreeVo) {
        List<CompanyParentTreeVo> resultList = new ArrayList<>();
        CompanyParentTreeVo parent = companyParentTreeVo.getParent();
        if (parent != null) {
            resultList.addAll(findParentCompanyList(parent));
        }
        resultList.add(companyParentTreeVo);
        return resultList;
    }
}
